package common

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"github.com/spf13/viper"
	"learningProject/vueGoProject/model"
)

// 全局的数据库对象
var (
	DB *gorm.DB
)

func InitMySQL() (err error) {
	driverName := viper.GetString("datasource.driverName")
	host := viper.GetString("datasource.host")
	port := viper.GetString("datasource.port")
	database := viper.GetString("datasource.database")
	username := viper.GetString("datasource.username")
	password := viper.GetString("datasource.password")
	charset := viper.GetString("datasource.charset")
	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
		username,
		password,
		host,
		port,
		database,
		charset)
	DB, err = gorm.Open(driverName, args)
	if err != nil {
		fmt.Println("连接数据库失败")
		return
	}
	err = DB.DB().Ping() // 测试连通性
	DB.AutoMigrate(&model.User{})
	return
}
